'use strict';

// const uuid = require("uuid")
exports.main = async (event, context) => {
	const { uuid } = event;
	
    const data = await uniCloud.request({
        url: "https://api.weixin.qq.com/sns/jscode2session",
        method: 'GET',
        data: {
            appid: 'wxf6ab670df0a89e37',
            secret: '51529562462349b6aebfc6c9c3950b31',
            js_code: event.code,
            grant_type: 'authorization_code'
        }
    })

    // 成功获取 wxOpenid，查询数据库判断一下是否已经注册
    const res = await uniCloud.database().collection("users").where({
        wxOpenid: data.data.openid
    }).get()


    if (!res?.data?.length) {
		const updateRes =  await uniCloud.database().collection("users").where({
			uuid
		}).update({
			wxOpenid: data.data.openid,
		})
		
        const userInfo = await uniCloud.database().collection("users").where({
			uuid
		}).get()
        return userInfo?.data?.[0]
    }

    //返回用户信息给前端
    return {
		code: 0,
		data: res?.data?.[0]
	}
};